// user_pkg/pages/address/address.js
Page({
  data: {
    addressList: [],
    defaultId: '',
    isDeleteShow: false,
    deleteAddressId: ''
  },
  onShow() {
    this.onRefreshPage()
  },
  // 刷新页面
  onRefreshPage() {
    this.getAddressList()
    this.getDefaultId()
  },
  // 获取收货地址列表
  async getAddressList() {
    const res = await wx.http.get('/address/list')
    const addressList = res.data.data.list
    this.setData({addressList})
  },
  // 获取默认收货地址ID
  async getDefaultId() {
    const res = await wx.http.get('/address/defaultId')
    const defaultId = res.data.data.defaultId
    this.setData({defaultId})
  },
  // 设置默认收货地址
  async setDefault(ev) {
    await wx.http.post('/address/setDefault', {
      addressId: ev.mark.addressId
    })
    this.onRefreshPage()
  },
  // 删除收货地址
  openModal(ev) {
    this.setData({
      isDeleteShow: true,
      deleteAddressId: ev.mark.addressId
    })
  },
  deleteCancel() {
    this.setData({
      isDeleteShow: false
    })
  },
  async deleteConfirm() {
    const res = await wx.http.post('/address/remove', {
      addressId: this.data.deleteAddressId
    })
    if(res.data.status === 200) {
      this.deleteCancel()
      this.onRefreshPage()
    } else {
      wx.showToast({
        title: '删除失败，请重试',
        icon: 'error'
      })
    }
  },
  // 新增收货地址
  addAddress() {
    wx.navigateTo({
      url: '../addaddress/addaddress',
    })
  },
  // 编辑收货地址
  editAddress(ev) {
    wx.navigateTo({
      url: `../addaddress/addaddress?addressId=${ev.mark.addressId}`,
    })
  }
})